import React, { Component } from 'react';
import {
  View,
  Text,
  Image,
  StatusBar,
  StyleSheet,
  AsyncStorage,
} from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';
import validator from '../../../utils/validator';
import { Input } from 'react-native-elements';
import { pxToDp } from '../../../utils/stylesKits';
import request from '../../../utils/request';
import { ACCOUNT_LOGIN, ACCOUNT_VALIDATEVCODE } from '../../../utils/pathMap';
import THButton from '../../../components/THButton';
import { CodeField, Cursor } from 'react-native-confirmation-code-field';
import Toast from '../../../utils/toast';
import { inject, observer } from 'mobx-react';
import JMessage from '../../../utils/JMessage';
@inject('RootStore')
@observer
class Index extends Component {
  state = {
    phoneNumber: '13512345678',
    // 手机号码是否合法 默认合法
    phoneValid: true,
    // 是否显示登陆页面 默认显示登陆页面
    showLogin: true,
    // 验证码输入框的值
    vcodeTxt: '',
    // 倒计时按钮的文本
    btnText: '重新获取',
    // 是否在倒计时中 默认不在
    isCountDowning: false,
  };
  // 登录框输入手机号码
  phoneNumberChangeText = (phoneNumber) => {
    this.setState({ phoneNumber });
  };
  // 手机号码点击完成的时候触发
  phoneNumberSubmitEditing = async () => {
    const { phoneNumber } = this.state;
    const phoneValid = validator.validataPhone(phoneNumber);
    console.log(phoneValid);
    if (!phoneValid) {
      // 没有通过
      this.setState({ phoneValid });
      return;
    }
    // 验证通过
    const res = await request.post(ACCOUNT_LOGIN, { phone: phoneNumber });
    if (res.code == '10000') {
      this.setState({ showLogin: false });
      // 开启定时器
      this.countDow();
    } else {
    }
    console.log(res);
  };
  // 开启获取验证码的定时器
  countDow = () => {
    if (this.state.isCountDowning) {
      return;
    }
    this.setState({ isCountDowning: true });
    let seconds = 5;
    // 重新获取5s
    this.setState({ btnText: `重新获取(${seconds}s)` });
    let timeId = setInterval(() => {
      seconds--;
      this.setState({ btnText: `重新获取(${seconds}s)` });
      if (seconds === 0) {
        clearInterval(timeId);
        this.setState({ btnText: '重新获取', isCountDowning: false });
      }
    }, 1000);
  };
  // 点击了重新获取按钮
  repGetVcode = () => {
    this.countDow();
  };
  // 验证码输入完成事件
  onVcodeOnSubmitEditing = async () => {
    /**
     * 校验验证码长度
     * 发送至后台
     * 后台返回值中有新旧用户的判断字段 isNew
     */

    const { vcodeTxt, phoneNumber } = this.state;
    console.log(vcodeTxt);
    if (vcodeTxt.length != 6) {
      Toast.message('验证码不正确', 2000, 'center');
      return;
    }

    const res = await request.post(ACCOUNT_VALIDATEVCODE, {
      phone: phoneNumber,
      vcode: vcodeTxt,
    });
    if (res.code != 10000) {
      console.log(res);
      return;
    }

    //  储存数据到mobx
    this.props.RootStore.setUserInfo(phoneNumber, res.data.token, res.data.id);
    // 存储用户数据到本地缓存
    AsyncStorage.setItem(
      'userinfo',
      JSON.stringify({
        mobile: phoneNumber,
        token: res.data.token,
        userId: res.data.id,
      }),
    );

    if (res.data.isNew) {
      this.props.navigation.navigate('UserInfo');
    } else {
      await JMessage.init();
      const res1 = await this.jglogin(
        this.props.RootStore.userId,
        this.props.RootStore.mobile,
      );
      this.props.navigation.navigate('Tabbar');
      alert('老用户');
    }
  };
  // 极光登录
  jglogin = async (username, password) => {
    return await JMessage.login(username, password);
  };
  // 渲染登陆页面
  renderLogin = () => {
    const { phoneNumber, phoneValid } = this.state;
    return (
      <View style={{ padding: pxToDp(20) }}>
        <View>
          <Text
            style={{ fontSize: pxToDp(25), color: '#888', fontWeight: 'bold' }}>
            手机号登录注册
          </Text>
        </View>
        {/* 输入框 */}
        <View style={{ marginTop: pxToDp(30) }}>
          <Input
            maxLength={11}
            keyboardType="phone-pad"
            inputStyle={{ color: '#333' }}
            onChangeText={this.phoneNumberChangeText}
            value={phoneNumber}
            placeholder="请输入手机号码"
            errorMessage={phoneValid ? '' : '手机号码格式不正确'}
            onSubmitEditing={this.phoneNumberSubmitEditing}
            leftIcon={{
              type: 'font-awesome',
              name: 'phone',
              color: '#ccc',
              size: pxToDp(20),
            }}
          />
        </View>
        {/* 渐变按钮 */}
        <View style={{ width: '75%', height: pxToDp(40), alignSelf: 'center' }}>
          <THButton
            onPress={this.phoneNumberSubmitEditing}
            style={{ borderRadius: pxToDp(20) }}>
            获取验证码
          </THButton>
        </View>
      </View>
    );
  };
  // 渲染获取验证码
  renderVcode = () => {
    const { phoneNumber, vcodeTxt, btnText, isCountDowning } = this.state;
    return (
      <View style={{ padding: pxToDp(20) }}>
        <View>
          <Text
            style={{ fontSize: pxToDp(25), color: '#888', fontWeight: 'bold' }}>
            输入6位验证码
          </Text>
        </View>
        <View style={{ marginTop: pxToDp(15) }}>
          <Text style={{ color: '#888' }}>已发到:86+ {phoneNumber}</Text>
        </View>
        <View>
          <CodeField
            value={vcodeTxt}
            onSubmitEditing={this.onVcodeOnSubmitEditing}
            onChangeText={this.onVcodeChangeText}
            cellCount={6}
            rootStyle={styles.codeFieldRoot}
            keyboardType="number-pad"
            renderCell={({ index, symbol, isFocused }) => (
              <Text
                key={index}
                style={[styles.cell, isFocused && styles.focusCell]}>
                {symbol || (isFocused ? <Cursor /> : null)}
              </Text>
            )}
          />
        </View>
        <View
          style={{
            marginTop: pxToDp(15),
            width: '75%',
            height: pxToDp(40),
            alignSelf: 'center',
          }}>
          <THButton
            disabled={isCountDowning}
            onPress={this.repGetVcode}
            style={{ borderRadius: pxToDp(20) }}>
            {btnText}
          </THButton>
        </View>
      </View>
    );
  };
  // 验证码输入框的值改变事件
  onVcodeChangeText = (vcodeTxt) => {
    console.log(vcodeTxt);
    this.setState({ vcodeTxt: vcodeTxt });
  };
  // 父子组件传值获取验证码
  handleGetVCode = () => {
    console.log('父子组件传值获取验证码');
  };
  render () {
    const { phoneNumber, phoneValid, showLogin } = this.state;
    return (
      <View>
        {/* 手机状态栏 */}
        <StatusBar backgroundColor="transparent" translucent={true} />
        {/* 背景图片 */}
        <Image
          style={{ width: '100%', height: pxToDp(200) }}
          source={require('../../../res/OIPz.jpg')}
        />
        {/* 内容 登陆 */}
        {/* 切换显示登陆和验证码 */}
        {showLogin ? this.renderLogin() : this.renderVcode()}
      </View>
    );
  }
}

const styles = StyleSheet.create({
  root: { flex: 1, padding: 20 },
  title: { textAlign: 'center', fontSize: 30 },
  codeFieldRoot: { marginTop: 20 },
  cell: {
    width: 40,
    height: 40,
    lineHeight: 38,
    fontSize: 24,
    borderBottomWidth: 2,
    borderColor: '#00000030',
    textAlign: 'center',
    color: '#7d53ea',
  },
  focusCell: {
    borderColor: '#7d53ea',
  },
});
export default Index;
